package psnl.bingo.bgtool.model.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import psnl.bingo.bgtool.model.constant.ConstSys;
import psnl.bingo.bgtool.model.dto.UserInfo;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
public class Login {
    @RequestMapping("/loginPage")
    public String loginPage() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        ModelMap model) {

        UserInfo userInfo = ConstSys.findUser(username);
        if(userInfo == null) {
            model.addAttribute("msg", "用户名不存在");
        }else if(userInfo.getName() == null){
            model.addAttribute("msg", "用户已过期");
        }else if(!userInfo.getPassword().equals(password)){
            model.addAttribute("msg", "密码错误");
        }

        if(model.containsKey("msg")) {
            return "login";
        }

        session.setMaxInactiveInterval(60 * 60 * 2);
        session.setAttribute("user", userInfo);

        return "redirect:/rename/index";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("user");
        return "login";
    }
}
